/**
 * 待配对家电信息 写入、删除逻辑
 * 缓存数据字段
 * @param vib 型号
 * @param type 类型
 * @param brand 品牌
 * @param scene 场景
 * @param catelog 类别
 * @param catelog_name 类别名称
 * @param count 展示次数
 */

/*
 * 1011	扫描二维码
 * 1012	长按图片识别二维码
 * 1013	扫描手机相册中选取的二维码
 * 1035	公众号自定义菜单
 * 1037	小程序打开小程序
 * 1047	扫描小程序码
 * 1048	长按图片识别小程序码
 * 1049	扫描手机相册中选取的小程序码
 * 1058	公众号文章
 * 1065 URL scheme
 * 1102	公众号profile页服务预览
 * 1167 H5 通过开放标签打开小程序
 */

import netconfig from '../config/netconfig.js'
import hcOfficialWeChatActivity from './hcOfficialWeChatActivity.js'
import { getCatelogByVib } from '../api/datareport'
import { useAuthStore } from '@/store/auth'
import store from '@/store'
import { useGlobalStore } from '@/store/global'
import loginHelper from '@/pluginHelper/login'
import {
  checkLocationPermission,
  OS_SYSTEM_LOCATION_PERMISSION,
  APPLICATION_LOCATION_PERMISSION,
  WXMP_LOCATION_PERMISSION,
} from './basicHelper.js'
import i18n from '@/i18n'
import { checkReason, showActionSheet, toPage } from '@/utils/mpHelper'

const authStore = useAuthStore(store)
let global = useGlobalStore(store)

// 设置待配对家电详细信息
export async function setPairingDetail(obj: any, sceneObj: any) {
  if (obj.scene) {
    //scene值有效的，才进行赋值
    sceneObj.sceneNumber = obj.scene
  }

  let scenes = [1011, 1012, 1013, 1035, 1047, 1048, 1049, 1058, 1065, 1102, 1167, 1194]
  let index = scenes.indexOf(obj.scene)
  if (index == -1) {
    console.log('setPairingDetail', obj.scene)
    return
  }
  let vib = ''
  let type = ''
  let brand = ''
  let scene = ''
  let catelog = ''
  let catelog_name = ''
  let catelog_pic = ''
  let hotSpotpwd = ''
  let count = 0
  let haId = ''
  if (obj.scene == 1065 || obj.scene == 1167) {
    // HCCN-3969 HC Official WeChat】Paring with E-Coupon from HC WeChat Button
    if (obj.query.scene != undefined && obj.query.scene != '') {
      hcOfficialWeChatActivity.saveHCOfficialWeChatMenuButtonActivty(obj.query.scene)
      scene = obj.query.scene
      sceneObj.sceneName = obj.query.scene
      global.scene = obj.query.scene
    }
  } else if (obj.scene == 1011 || obj.scene == 1012 || obj.scene == 1013) {
    let url = decodeURIComponent(obj.query.q)
    let urlArr = url.split('?')
    if (urlArr.length < 2) {
      return
    }
    let queryArr = urlArr[1].split('&')

    interface QueryObject {
      [key: string]: any
    }
    let queryObj: QueryObject = {}

    // 遍历数组
    queryArr.forEach(function (val) {
      // 切割=两边的数据
      let query = val.split('=')
      queryObj[query[0]] = query[1]
    })
    if (queryObj.vib) {
      vib = queryObj.vib
    }
    if (queryObj.pd) {
      global.hotSpotpwd = queryObj.pd
      hotSpotpwd = queryObj.pd
    }
    if (queryObj.scene) {
      scene = queryObj.scene
      sceneObj.sceneName = queryObj.scene
      global.scene = obj.query.scene
    }
  } else {
    if (obj.query.vib) {
      vib = obj.query.vib
      haId = obj.query.haId
    }
    if (obj.query.scene) {
      scene = obj.query.scene
      sceneObj.sceneName = obj.query.scene
      global.scene = obj.query.scene
    }
  }
  if (vib && !haId) {
    let pairingSource: string
    if (sceneObj.sceneName == 'device') {
      pairingSource = '机器码'
    } else if (sceneObj.sceneName == 'manual') {
      pairingSource = '手册码'
    } else {
      if (global.hotSpotpwd) {
        //适配TT一机一密
        pairingSource = '机器码'
      } else {
        pairingSource = '其他渠道'
      }
    }
    // 检查登录信息
    console.error('pairingSource', pairingSource, 'vib', vib, 'hotSpotpwd', global.hotSpotpwd)
    const pairingPath = `/pages/pairing/confirmAppliance/index?vib=${vib}&pairingSource=${pairingSource}&hotSpotpwd=${global.hotSpotpwd}`

    toPage(pairingPath)
    // let res = await getCatelogByVib(vib)
    // if (res.code == 0 && res.data.launched === 0) {
    //   if (res.data.catelog) {
    //     catelog = res.data.catelog
    //   }
    //   if (res.data.catelog_name) {
    //     catelog_name = res.data.catelog_name
    //   }
    //   if (res.data.catelog_pic) {
    //     catelog_pic = res.data.catelog_pic
    //   }
    //   if (res.data.type) {
    //     type = res.data.type
    //   }
    //   if (res.data.brand) {
    //     brand = res.data.brand
    //   }
    //   let detail = {
    //     vib,
    //     type,
    //     brand,
    //     scene,
    //     catelog,
    //     catelog_name,
    //     catelog_pic,
    //     count,
    //   }
    //   uni.setStorageSync('HAWaitForPairing', detail)
    // } else {
    // }
  }

  // 数据分析 打开小程序时候上报
  if (scene != null) {
    uni.reportAnalytics('launch_scene', {
      scene,
      scene_vib: vib,
      scene_brand: brand,
      scene_type: type,
    })
  }
}

export function getPairingDetail(count: any) {
  let detail = wx.getStorageSync('HAWaitForPairing')
  if (detail == undefined || detail == null || detail == '') {
    detail = {}
  }
  if (detail.count && detail.count != count) {
    detail = {}
  }
  return detail
}

export function updatePairingDetail(detail: any) {
  if (detail.count == 0) {
    detail.count = detail.count + 1
    // wx.setStorage({
    //   key: 'HAWaitForPairing',
    //   data: detail,
    // });
    uni.setStorageSync('HAWaitForPairing', detail)
  } else {
    uni.removeStorageSync('HAWaitForPairing')
    // wx.removeStorage({
    //   key: 'HAWaitForPairing',
    //   success(res) {},
    // });
  }
}

export function removePairingDetail() {
  uni.removeStorageSync('HAWaitForPairing')
  // wx.removeStorage({
  //   key: 'HAWaitForPairing',
  //   success(res) {},
  // });
}

export async function initPairingApplianceDetail(vib: string, scene: any) {
  let catelog = ''
  let catelog_name = ''
  let catelog_pic = ''
  let count = 0
  let type = ''
  let brand = ''
  if (vib) {
    let res = await getCatelogByVib(vib)
    if (res.code == 0 && res.data.launched === 0) {
      if (res.data.catelog) {
        catelog = res.data.catelog
      }
      if (res.data.catelog_name) {
        catelog_name = res.data.catelog_name
      }
      if (res.data.catelog_pic) {
        catelog_pic = res.data.catelog_pic
      }
      if (res.data.type) {
        type = res.data.type
      }
      if (res.data.brand) {
        brand = res.data.brand
      }
      let detail = {
        vib,
        type,
        brand,
        scene,
        catelog,
        catelog_name,
        catelog_pic,
        count,
      }
      try {
        uni.setStorageSync('PairingAppliance', detail)
      } catch (e) {
        console.error('setStorageSync is fail:', e)
      }
      // 数据分析 打开小程序时候上报
      if (scene != null) {
        uni.reportAnalytics('launch_scene', {
          scene,
          scene_vib: vib,
          scene_brand: brand,
          scene_type: type,
        })
      }
    } else {
    }
  }
}

/**
 * 家电离线重连
 */

export function reConnect(vib: string | undefined, pairingSource: string) {
  requirePlugin(
    'pairing-plugin',
    (plugin) => {
      plugin.initPluginHttpEnvironment(netconfig.PLUGIN_ENV, netconfig.isTester)
      plugin.initPluginData(authStore.accessToken, authStore.accessOpenId, authStore.key, authStore.iv)

      plugin.initPairingDeviceData(
        vib,
        '',
        pairingSource,
        false,
        global.sceneNumber,
        global.sceneName,
        global.sucPage,
        this,
        (obj: any) => {
          uni.navigateTo({
            url: obj.url,
            success: (res) => {
              console.log('success', res)
              uni.hideLoading()
            },
            fail: (error) => {
              console.error('fail', error)
            },
            complete: () => {},
          })
        },
        global.hotSpotpwd,
        '',
        'HC3.0'
      )
    },
    ({ mod, errMsg }) => {
      uni.hideLoading()
      uni.showToast({
        title: '加载异常，请稍后再试',
        icon: 'none',
      })
    }
  )
  // }
}
